package com.autoool.utils;

import com.sun.javafx.fxml.builder.URLBuilder;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author sam
 * 2021/7/4 21:43
 * @description
 * @editor
 * @description
 */
public class HttpClientUtil {

    public static String doGet(String url) throws IOException, URISyntaxException {
        return doGet(url, Collections.emptyMap());
    }

    public static String doGet(String url, final Map<String, Object> query) throws IOException, URISyntaxException {
        return doGet(url, Collections.emptyMap(), query);
    }

    public static String doGet(String url, final Map<String, Object> header, final Map<String, Object> query) throws IOException, URISyntaxException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        URIBuilder uriBuilder = new URIBuilder(url);
        if (!query.isEmpty()) {
            List<NameValuePair> valuePairs = new ArrayList<>();
            query.forEach((key, value) -> {
                valuePairs.add(new BasicNameValuePair(key, String.valueOf(value)));
            });
        }
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        CloseableHttpResponse response = null;
        if (!header.isEmpty()) {
            header.forEach((key, value) -> {
                httpGet.addHeader(key, String.valueOf(value));
            });
        }


        try {
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String content = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                return content;
            }
        } finally {
            if (response != null) {
                response.close();
            }
            httpClient.close();
        }
        return null;
    }
}
